﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using EPiServer.PlugIn;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace EPiServer.Research.UI.CssEditor
{
    public class CssDB
    {
        private static DataSet _cssDb = null;
        private static object lockme = new object();
        public static DataSet loadSetting()
        {
            if (_cssDb == null)
            {
                _cssDb = new DataSet();
                DataTable dt = _cssDb.Tables.Add();
                dt.Columns.Add("pageid");
                dt.Columns.Add("classname");
                dt.Columns.Add("classstring");
                
                PlugInSettings.Populate(typeof(EPiServer.Research.UI.CssEditor.CssDB), _cssDb);
                //DataRow dr = _cssDb.Tables[0].NewRow();
                //dr["pageid"] = 3;
                //dr["classname"] = "p";
                //dr["classstring"] = "font:2";
                //_cssDb.Tables[0].Rows.Add(dr);
            }
            return _cssDb;
        }

        public static void saveSetting(int pageid,string[] rulenames,string[] rulevalues)
        {
            lock (lockme)
            {
                DataSet ds = loadSetting();
                DataTable dt = ds.Tables[0];

                List<int> rowids = new List<int>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(dt.Rows[i]["pageid"] as string) == pageid)
                        rowids.Add(i);
                }
                for (int i=rowids.Count-1;i>=0;i--)
                {
                    dt.Rows.RemoveAt(rowids[i]);
                }

                for (int j=0;j<rulenames.Length;j++)
                {
                    DataRow dr = dt.NewRow();
                    dr["pageid"] = pageid;
                    dr["classname"] = rulenames[j];
                    dr["classstring"] = rulevalues[j];
                    dt.Rows.Add(dr);
                }
                PlugInSettings.Save(typeof(EPiServer.Research.UI.CssEditor.CssDB), ds);
            }
        }
    }
}
